package com.springmvc.controller;

import com.springmvc.entity.User;
import com.springmvc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @RequestMapping("/add")
    public String add(Model model,Long id){
        if(id!=null){
            User user = userService.getById(id);
            model.addAttribute("user",user);
        }
        return "user/add";
    }

    @RequestMapping("/save")
    @ResponseBody
    public Boolean save(@RequestBody User user){

        return userService.saveOrUpdate(user);
    }

    @RequestMapping("/delById")
    public String delById(Long id){
        if(id!=null){
            userService.delById(id);
        }
        return "redirect:/home";
    }

    @RequestMapping("/delAll")
    @ResponseBody
    public Boolean delAll(@RequestBody List<String> ids){
        for (String id : ids) {
            userService.delById(Long.parseLong(id));
        }
        return true;
    }

}